﻿using System;
using System.Windows.Controls;
using StartupSolution.DataServiceReference1;
using Infragistics.Collections;

namespace StartupSolution.Views.Grids
{
    public partial class LargeSets : UserControl
    {
        DataServiceClient SerRefClient;
        VirtualCollection<DataServiceReference1.TestData> vc;

        public LargeSets()
        {
            InitializeComponent();

            SerRefClient = new DataServiceClient();

            SerRefClient.GetTestDataCountAsync();

            SerRefClient.GetTestDataCountCompleted += new EventHandler<GetTestDataCountCompletedEventArgs>(SerRefClient_GetTestDataCountCompleted);
            SerRefClient.GetTestDataCompleted += new EventHandler<GetTestDataCompletedEventArgs>(SerRefClient_GetTestDataCompleted);
        }

        void SerRefClient_GetTestDataCompleted(object sender, GetTestDataCompletedEventArgs e)
        {
            int count = e.Result.DataItems.Count;
           
            // When data is received from the service - load it in the Virtual Collection, so the XamGrid can display it
            // Load the list of items into the Virtual Collection cache
            vc.LoadItems(e.Result.StartIndex, e.Result.DataItems);
        }

        void SerRefClient_GetTestDataCountCompleted(object sender, GetTestDataCountCompletedEventArgs e)
        {
            int count = e.Result;

            // create the Vitual Collection, with the received anticipated size from the service
            vc = new VirtualCollection<DataServiceReference1.TestData>(count);
            
            // Attach a handler for ItemDataRequested event
            vc.ItemDataRequested += new EventHandler<ItemDataRequestedEventArgs>(vc_ItemDataRequested);
            
            // Virtual collection contains only a portion of all data records, set their number with the LoadSize property
            vc.LoadSize = 12;

            // Set the Virtual Collection as XamGrid ItemsSource
            this.dataGrid.ItemsSource = vc;
        }

        void vc_ItemDataRequested(object sender, ItemDataRequestedEventArgs e)
        {
            // When the XamGrid is requesting data, pass the async request to the service
            SerRefClient.GetTestDataAsync(e.StartIndex, e.ItemsCount);
        }

    }
}
